<script setup lang="ts">
import {ref, useTemplateRef} from "vue";
import {useRouter} from "vue-router";
import {showFailToast, showSuccessToast} from "vant";
import myAxios from "../../plugins/MyAxios.ts";

const username = ref<string>();
const password = ref<string>();
const form = useTemplateRef('form');

const checkUserName = () => {
  if (username.value === null || username.value === "" || username.value === undefined) {
    return false;
  }else if (username.value.length < 4) {
    return false;
  }
  return true;
}

const checkPassword = () => {
  if (password.value === null || password.value === "" || password.value === undefined) {
    return false;
  }
  if (password.value.length < 8) {
    return false;
  }
  const regex = /[^a-zA-Z0-9]/; // 匹配任何非字母和非数字的字符
  return !regex.test(password.value);
}

const login = async () => {
  try {
    const formRef = form.value as any;
    await formRef.validate();
    const result = await myAxios.post('/user/login', {
      userAccount: username.value,
      userPassword: password.value
    });
    if (result.data.code !== 200) {
      showFailToast('账号或密码错误');
    }else {
      showSuccessToast('登录成功');
      await router.push('/home/friends')
    }
  } catch (e) {
    showFailToast('网络异常');
    console.log(e);
  }
}

const router = useRouter();
const register = () => {
  router.push('/register')
}

</script>

<template>
  <div class="form">
    <van-form ref="form" >
      <van-cell-group inset>
        <van-field
            v-model="username"
            name="username"
            label="用户账号"
            placeholder="请输入用户账号"
            :rules="[{ required: true, validator : checkUserName ,message: '用户账号长度不小于4' }]"
        />
        <van-field
            v-model="password"
            type="password"
            name="password"
            label="密码"
            placeholder="请输入密码"
            :rules="[{ required: true, validator: checkPassword, message: '密码长度不小于8,不能包含特殊字符' }]"
        />
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit" @click="login">
          登录
        </van-button>
      </div>
    </van-form>
    <div style="margin: 16px;">
      <van-button round block type="primary" @click="register">
        注册
      </van-button>
    </div>
  </div>
</template>

<style scoped>
.form {
  margin: 150px auto;
}
</style>